package com.xspace.android.imcommon.interfaces;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;

import com.xspace.android.imcommon.entity.ChatMsg;
import com.xspace.android.imcommon.entity.ChatMsgSnap;
import com.xspace.android.imcommon.entity.DBSMSBean;
import com.xspace.android.imcommon.entity.Friend;
import com.xspace.android.imcommon.entity.PushMsg;
import com.xspace.android.imcommon.fileupload.IUploadCallback;
import com.xspace.android.imcommon.fileupload.IuploadListener;
import com.xspace.android.imcommon.interfaces.ChatCallback.Stub;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;


public class ServiceManager {
    private static ServiceManager instance = null;
    protected static ServiceRemoteConnection remoteConn = null;
    private final Context context;
    private String serviceName;
    private Vector<ConnectedListener> connVector = new Vector<ConnectedListener>();

    protected static ServiceManager getInstance(Context context, String serviceName) {

        if (null == instance || remoteConn == null) {
            System.out.println("instance ==null");
            instance = new ServiceManager(context, serviceName);
        }
        return instance;
    }

    private ServiceManager(Context context, String serviceName) {
        this.context = context;
        this.serviceName = serviceName;
        remoteConn = new ServiceRemoteConnection();
        remoteConn.initRemoteConnection();
    }

    protected void initSendMessage(final IToMsgListener callback, final String userName, final String toUserName) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.initSendMessage(new TransportCallback(callback), userName, toUserName);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.initSendMessage(new TransportCallback(callback), userName, toUserName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void initChatInfoMessage(final IToChatListener mcallback) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.initChat(new MChatCallback(mcallback));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.initChat(new MChatCallback(mcallback));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void sendMg(final ChatAidl info) throws RemoteException {

        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.sendMessage(info);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.sendMessage(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void sendMucMg(final MucChatAidl info) throws RemoteException {

        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.i("servicemanager", "****sendMucMg***");
                        remoteConn.messageService.sendMucMsg(info);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.sendMucMsg(info);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void inviteFriendToRoom(final String roomId, final String userId,
                                      final String reason) throws RemoteException {

        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.i("servicemanager", "****inviteFriendToRoom***");
                        remoteConn.messageService.inviteFriendToRoom(roomId, userId, reason);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                Log.i("servicemanager", "****inviteFriendToRoom***");
                remoteConn.messageService.inviteFriendToRoom(roomId, userId, reason);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void joinToRoom(final String roomId, final String userId, final String nickname) throws RemoteException {

        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.v("servicemanager", "****joinToRoom00***" + roomId);
                        remoteConn.messageService.joinToRoom(roomId, userId, nickname);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                Log.v("servicemanager", "****joinToRoom11***" + roomId);
                remoteConn.messageService.joinToRoom(roomId, userId, nickname);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void kickFriendFromRoom(final String roomId, final String userId, final String reason) throws RemoteException {

        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.i("servicemanager", "****kickFromRoom***");
                        remoteConn.messageService.kickFriendFromRoom(roomId, userId, reason);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                Log.i("servicemanager", "****kickFromRoom***");
                remoteConn.messageService.kickFriendFromRoom(roomId, userId, reason);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected String CreateMucRoom(final String nickname, final String userId) throws RemoteException {
        String rid = null;
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.i("imcommon", "servicemanager****CreateMucRoom00***");
                        //String roomid=remoteConn.messageService.createMucRoom(nickname, userId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                Log.i("imcommon", "servicemanager****CreateMucRoom11***");
                rid = remoteConn.messageService.createMucRoom(nickname, userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rid;
    }

    protected void exitMucRoom(final String roomId) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        Log.i("imcommon", "servicemanager****exitMucRoom00***");
                        remoteConn.messageService.exitMucRoom(roomId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                Log.i("imcommon", "servicemanager****exitMucRoom***");
                remoteConn.messageService.exitMucRoom(roomId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void queryMsgList(final int startRecord, final int pageSize) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.queryMsgList(startRecord, pageSize);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.queryMsgList(startRecord, pageSize);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void queryHistoryMsgList() throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.queryHistoryMsgList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.queryHistoryMsgList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void queryFriendInfo(final String owner, final String userId, final IFriendListener mIFriendListener) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.queryFriend(owner, userId, new TranFriendCallback(mIFriendListener));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.queryFriend(owner, userId, new TranFriendCallback(mIFriendListener));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void queryFriendMsgList(final String userId, final IFriendListener mIFriendListener) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.queryListFriend(userId, new TranFriendCallback(mIFriendListener));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.queryListFriend(userId, new TranFriendCallback(mIFriendListener));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void saveOrUpdateFriend(final Friend info, final String userId) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.saveOrUpdateFriend(new FriendAidl(info), userId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.saveOrUpdateFriend(new FriendAidl(info), userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected boolean addFriend(String mBarejid, String mName, String mMobile) {
        try {
            return remoteConn.messageService.addFriend(mBarejid, mName, mMobile);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    protected void getServerFriendList() {
        try {
            remoteConn.messageService.getAllServerFriends();
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    protected boolean deleteFriend(String mBarejid) {
        try {
            return remoteConn.messageService.deleteFriend(mBarejid);
        } catch (RemoteException e) {
            e.printStackTrace();
            return false;
        }

    }

    protected void removeIToUserListener(String key) {
        try {
            mItoUserMap.remove(key);
        } catch (Exception e) {

        }
    }

    protected void initImUser(final String key, final String owner, final IToUserListener callback, final int pageSize) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.initImUser(owner, new TranNgpCallback(key, callback), pageSize);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.initImUser(owner, new TranNgpCallback(key, callback), pageSize);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void queryUserList() throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.queryHistoryMsgList();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.queryHistoryMsgList();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    protected void updateUserUnread(final int userId, final int unread) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.updateUserUnread(userId, unread);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.updateUserUnread(userId, unread);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void updateUserInfo(final String userId, final String userName, final String userHead, final int whiteStatus) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.updateUserInfo(userId, userName, userHead, whiteStatus);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.updateUserInfo(userId, userName, userHead, whiteStatus);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void unImUser() throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.unImUser();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.unImUser();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void unSendMessage() throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.unSendMessage();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.unSendMessage();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void userLogin(final int iocId, final String userName, final String password, final String host, final int port, final String url, final ILoginListener listener)
            throws RemoteException {
        System.out.println("-----------------------remoteConn.messageService:" + remoteConn.messageService);
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.login(iocId, userName,
                                password, host, port, url,
                                new TranUserCallback(listener));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.login(iocId, userName, password, host, port, url, new TranUserCallback(listener));
            } catch (Exception e) {
                e.printStackTrace();
                ImServiceConnection.stop();
            }
        }
    }

    protected void userLogout() throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.logOut();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.logOut();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        remoteConn.releaseRemoteConnection();
    }

    protected void unbindService() {
        try {
            if (null != remoteConn) {
                remoteConn.releaseRemoteConnection();
            }
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            remoteConn = null;
        }

        if (null != instance) {
            instance = null;
        }
    }

    protected void initPush(final IToPushListener mListener) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.initPush(new TranPushCallback(mListener));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.initPush(new TranPushCallback(mListener));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    // push
    protected PushListAidl queryLatestPushMsgs(final String barejid, String channelName) throws RemoteException {
        try {
            return remoteConn.messageService.queryPushList(barejid, channelName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    protected PushListAidl queryPushChildList(String mPushUserID, String mPlatformID, String owner, String sendtimeStart, String sendtimeEnd, String key) throws RemoteException {
        try {
            return remoteConn.messageService.queryPushChildList(mPushUserID, mPlatformID, owner, sendtimeStart, sendtimeEnd, key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    protected PushListAidl queryPushChildAllList(String owner, String channelName) throws RemoteException {
        try {
            return remoteConn.messageService.queryPushChildAllList(owner, channelName);
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    protected List<String> getMsgBodyTypeArr() throws RemoteException {
        try {
            return remoteConn.messageService.getMsgBodyTypeArr();
        } catch (Exception e) {
            e.printStackTrace();
            return null;

        }

    }

    protected void saveOrUpdatePush(final String owner, final PushAidl pushMsg) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.saveOrUpdatePush(owner, pushMsg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.saveOrUpdatePush(owner, pushMsg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void updateUnReadPushCount(final String owner, final PushAidl pushMsg) throws RemoteException {
        //Log.i("pushdb", "updateunreadcount servicemanager  pushMsg:"+pushMsg+" owner:"+owner);
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.updateUnReadPushCount(owner, pushMsg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.updateUnReadPushCount(owner, pushMsg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void deleteSinglePushMsg(final int msgId) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.deleteSinglePushMsg(msgId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.deleteSinglePushMsg(msgId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    protected void deletePushMsg(final String mPlatformId, final String pushUserID, final String barejid) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.deletePushMsg(mPlatformId, pushUserID, barejid);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.deletePushMsg(mPlatformId, pushUserID, barejid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean isNotifyAlert() {
        try {
            return remoteConn.messageService.isNotifyAlert();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean isNotifyvibation() {
        try {
            return remoteConn.messageService.isNotifyvibation();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean isNotifyOpen() {
        try {
            return remoteConn.messageService.isNotifyOpen();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean setNotifyAlert(boolean flag) {
        try {
            return remoteConn.messageService.setNotifyAlert(flag);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean setNotifyvibation(boolean flag) {
        try {
            return remoteConn.messageService.setNotifyvibation(flag);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    boolean setNotifyOpen(boolean flag) {
        try {
            return remoteConn.messageService.setNotifyOpen(flag);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // sms
    public void initSms(final IToSMSListener mListener) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.initSms(new TranSmsCallback(mListener));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.initSms(new TranSmsCallback(mListener));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public SmsListAidl querySmsList(final String smsType, final String jid) throws RemoteException {

        try {
            return remoteConn.messageService.querySmsList(smsType, jid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public void deleteSmsInfo(String smsType, int id) throws RemoteException {
        remoteConn.messageService.deleteSmsInfo(smsType, id);
    }

    public void unReadQury(final String jid) throws RemoteException {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.unReadSmsQury(jid);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.unReadSmsQury(jid);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void updateSmsRead(String smsType, String userId) throws RemoteException {
        remoteConn.messageService.updateSmsRead(smsType, userId);
    }

    private IToSMSListener mIToSMSListener;

    private class TranSmsCallback extends SMSCallback.Stub {
        public TranSmsCallback(IToSMSListener listener) {
            mIToSMSListener = listener;
        }

        @Override
        public void onToUnRead(int unreadSize, String smsType) throws RemoteException {
            // TODO Auto-generated method stub
            if (mIToSMSListener != null) {
                Bundle b = new Bundle();
                b.putString("result", smsType);
                b.putInt("msg", unreadSize);
                Message m = mHandler.obtainMessage(10);
                m.setData(b);
                mHandler.sendMessage(m);
            }
        }

        @Override
        public void onToSMSInfo(SmsBeanAidl info, String smsType) throws RemoteException {
            // TODO Auto-generated method stub
            if (mIToSMSListener != null) {
                Bundle b = new Bundle();
                b.putString("result", smsType);
                b.putSerializable("msg", info.info);
                Message m = mHandler.obtainMessage(11);
                m.setData(b);
                mHandler.sendMessage(m);
            }
        }

    }

    //	private IToUserListener mIToUserListener;
    private HashMap<String, IToUserListener> mItoUserMap = new HashMap<String, IToUserListener>();

    private class TranNgpCallback extends ChatSnapCallback.Stub {
        public TranNgpCallback(String key, IToUserListener listener) {
//			mIToUserListener = listener;
            mItoUserMap.put(key, listener);
        }

        @Override
        public void onToChatSnapList(ChatSnapListAidl chatSnapList) throws RemoteException {
            // TODO Auto-generated method stub
            if (mItoUserMap != null && mItoUserMap.size() > 0) {
                Message m = mHandler.obtainMessage(6, chatSnapList.respList);
                mHandler.sendMessage(m);
            }
        }

        @Override
        public void onToChatSnapInfo(ChatSnapAidl chatSnapInfo) throws RemoteException {
            // TODO Auto-generated method stub
            if (mItoUserMap != null && mItoUserMap.size() > 0) {
                Message m = mHandler.obtainMessage(7, chatSnapInfo.info);
                mHandler.sendMessage(m);
            }
        }

        @Override
        public void onDeleteUser(String userId) throws RemoteException {
            // TODO Auto-generated method stub
            if (mItoUserMap != null && mItoUserMap.size() > 0) {
                Message m = mHandler.obtainMessage(13, userId);
                mHandler.sendMessage(m);
            }
        }

    }

    private IToMsgListener mListener;

    private class TransportCallback extends IMsgCallback.Stub {

        public TransportCallback(IToMsgListener listener) {
            mListener = listener;
        }

        @Override
        public void onToMessage(ChatAidl info) throws RemoteException {
            if (mListener != null) {
                Message m = mHandler.obtainMessage(0, info.info);
                mHandler.sendMessage(m);
            }
        }

        @Override
        public void queryMsgList(ChatListAidl msgList) throws RemoteException {
            if (mListener != null) {
                Message m = mHandler.obtainMessage(1, msgList.respList);
                mHandler.sendMessage(m);
            }
        }

        @Override
        public void onChangeState(ChatAidl info) throws RemoteException {
            if (mListener != null) {
                Message m = mHandler.obtainMessage(2, info.info);
                mHandler.sendMessage(m);
            }

        }

        @Override
        public void onClearMsg(String userId) throws RemoteException {
            // TODO Auto-generated method stub
            if (mListener != null) {
                Message m = mHandler.obtainMessage(12, userId);
                mHandler.sendMessage(m);
            }
        }

    }

    private IToChatListener mChatListener;

    private class MChatCallback extends Stub {
        public MChatCallback(IToChatListener mChatListener1) {
            mChatListener = mChatListener1;
        }

        @Override
        public void onToChatInfo(ChatAidl chatInfo) throws RemoteException {
            if (mChatListener != null) {
                Message m = mHandler.obtainMessage(14, chatInfo.info);
                mHandler.sendMessage(m);
            }

        }

    }

    private IFriendListener mIFriendListener;

    private class TranFriendCallback extends FriendCallback.Stub {

        public TranFriendCallback(IFriendListener mIFriendListeners) {
            mIFriendListener = mIFriendListeners;
        }

        @Override
        public void onToFriend(FriendAidl info) throws RemoteException {
            if (mIFriendListener != null) {
                Message m = mHandler.obtainMessage(4, info.info);
                mHandler.sendMessage(m);
            }

        }

        @Override
        public void onToFriendList(FriendListAidl mList) throws RemoteException {
            System.out.println("============mList.respList:" + mList.respList.size());
            if (mIFriendListener != null) {
                Message m = mHandler.obtainMessage(5, mList.respList);
                mHandler.sendMessage(m);
            }

        }

        @Override
        public void onToFriendMap(FriendMapAidl mMap) throws RemoteException {
            // TODO Auto-generated method stub

        }

    }

    private IToPushListener mIToPushListener;

    private class TranPushCallback extends PushCallback.Stub {
        public TranPushCallback(IToPushListener listener) {
            mIToPushListener = listener;
        }

        @Override
        public void onToPushList(PushListAidl pushList) throws RemoteException {
            if (mIToPushListener != null) {
                Message m = mHandler.obtainMessage(8, pushList.respList);
                mHandler.sendMessage(m);
            }

        }

        @Override
        public void onToPushInfo(PushAidl pushInfo) throws RemoteException {
            // TODO Auto-generated method stub
            if (mIToPushListener != null) {
                Message m = mHandler.obtainMessage(9, pushInfo.info);
                mHandler.sendMessage(m);
            }
        }

    }

    private ILoginListener mUListener;

    private class TranUserCallback extends LoginCallBack.Stub {

        public TranUserCallback(ILoginListener listener) {
            mUListener = listener;
        }

        @Override
        public void callBack(boolean result, String msg) throws RemoteException {
            // TODO Auto-generated method stub
            if (mUListener != null) {
                Bundle b = new Bundle();
                b.putBoolean("result", result);
                b.putString("msg", msg);
                Message m = mHandler.obtainMessage(3);
                m.setData(b);
                mHandler.sendMessage(m);
            }
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mListener.onToMessage((ChatMsg) msg.obj);
                    break;
                case 1:
                    mListener.onQueryMsgList((ArrayList<ChatMsg>) msg.obj);
                    break;
                case 2:
                    mListener.onChangeState((ChatMsg) msg.obj);
                    break;
                case 3:
                    Bundle s = msg.getData();
                    mUListener.callBack(s.getBoolean("result"), s.getString("msg"));
                    break;
                case 4:
                    mIFriendListener.onToFriend((Friend) msg.obj);
                    break;
                case 5:
                    mIFriendListener.onToFriendList((ArrayList<Friend>) msg.obj);
                    break;
                case 6:
//				mIToUserListener.onToNewMsgList((ArrayList<ChatMsgSnap>) msg.obj);
                    Iterator<Map.Entry<String, IToUserListener>> iter = mItoUserMap
                            .entrySet().iterator();
                    while (iter.hasNext()) {
                        Map.Entry<String, IToUserListener> entry = iter.next();
                        Object key = entry.getKey();
                        IToUserListener mListener = mItoUserMap.get(key);
                        mListener.onToNewMsgList((ArrayList<ChatMsgSnap>) msg.obj);
                    }
                    break;
                case 7:
//				mIToUserListener.onToNewMsg((ChatMsgSnap) msg.obj);
                    Iterator<Map.Entry<String, IToUserListener>> iters = mItoUserMap
                            .entrySet().iterator();
                    while (iters.hasNext()) {
                        Map.Entry<String, IToUserListener> entry = iters.next();
                        Object key = entry.getKey();
                        IToUserListener mListener = mItoUserMap.get(key);
                        mListener.onToNewMsg((ChatMsgSnap) msg.obj);
                    }
                    break;
                case 8:
                    mIToPushListener.onToPushList((ArrayList<PushMsg>) msg.obj);
                    break;
                case 9:
                    mIToPushListener.onToPushInfo((PushMsg) msg.obj);
                    break;
                case 10:
                    Bundle ms = msg.getData();
                    mIToSMSListener.onToUnRead(ms.getInt("msg"), ms.getString("result"));
                    break;
                case 11:
                    Bundle msl = msg.getData();
                    mIToSMSListener.onToSMSInfo((DBSMSBean) msl.getParcelable("msg"), msl.getString("result"));
                    break;
                case 12:
                    mListener.onClearMsg((String) msg.obj);
                    break;

                case 13:
//				mIToUserListener.onDeleteUser((String) msg.obj);
                    Iterator<Map.Entry<String, IToUserListener>> iterd = mItoUserMap
                            .entrySet().iterator();
                    while (iterd.hasNext()) {
                        Map.Entry<String, IToUserListener> entry = iterd.next();
                        Object key = entry.getKey();
                        IToUserListener mListener = mItoUserMap.get(key);
                        mListener.onDeleteUser((String) msg.obj);
                    }
                    break;
                case 14:
                    mChatListener.onToNewMsg((ChatMsg) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };

    private interface ConnectedListener {
        void callBack();
    }

    protected boolean isBind() {
        return remoteConn.isBound;
    }

    private class ServiceRemoteConnection implements ServiceConnection {
        private boolean isBound = false;

        private IMessage messageService = null;

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            messageService = IMessage.Stub.asInterface(service);
            for (int j = 0; j < connVector.size(); j++) {
                connVector.get(j).callBack();
            }
            connVector.clear();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            messageService = null;
        }

        public boolean initRemoteConnection() {
            System.out.println("initRemoteConnection ==isBound >>" + isBound + ">>serviceName>>" + serviceName);
            if (!isBound) {
                Intent i = new Intent(serviceName);
                i.setPackage(context.getPackageName());
                isBound = context.bindService(i, this, Context.BIND_AUTO_CREATE);
                System.out.println("initRemoteConnection ==isBound result >>" + isBound + ">>serviceName>>" + serviceName);
            }
            return isBound;
        }

        public void releaseRemoteConnection() {
            if (isBound == true) {
                Log.i("clientservice", "*************releaseRemoteConnection unbindService*************");
                context.unbindService(this);
            }
            isBound = false;
        }
    }

    public void deleteImUser(final String userId) {
        if (remoteConn.messageService == null) {
            connVector.add(new ConnectedListener() {
                @Override
                public void callBack() {
                    try {
                        remoteConn.messageService.deleteImUser(userId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        } else {
            try {
                remoteConn.messageService.deleteImUser(userId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public boolean deleteMsg(final int msgId) {
        try {
            return remoteConn.messageService.deleteMsg(msgId);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public void upload(ChatListAidl uploadList, IuploadListener mListener)
            throws RemoteException {
        remoteConn.messageService.fileUpload(uploadList,
                new TransportLoadCallback(mListener));
    }

    public void initIuploadListener(IuploadListener listener) throws RemoteException {
        mUploadListener = listener;
    }

    public synchronized void resetCallback(long id, IuploadListener listener) throws RemoteException {
        remoteConn.messageService.resetCallback(id, new TransportLoadCallback(listener));
    }

    public ChatListAidl queryUploadList(String fromUserId, String toUserId)
            throws Exception {
        return remoteConn.messageService.queryUploadList(fromUserId, toUserId);
    }

    public void deleteFileMsg(long msgId)
            throws RemoteException {
        remoteConn.messageService.deleteFileMsg(msgId);
    }

    private IuploadListener mUploadListener;

    private class TransportLoadCallback extends IUploadCallback.Stub {


        public TransportLoadCallback(IuploadListener listener) {
            mUploadListener = listener;
        }

        @Override
        public void onUploadBefore(ChatAidl uploads) throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onUploadBefore(uploads.info);
            }
        }

        @Override
        public void onUploading(int position, long uploaded, long total,
                                float progress, float speed, ChatAidl uploads, int current)
                throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onUploading(position, uploaded, total, progress, speed,
                        uploads.info, current);
            }
        }

        @Override
        public void onUploadError(int position, long uploaded, float progress,
                                  ChatAidl uploads, int current) throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onUploadError(position, uploaded, progress, uploads.info,
                        current);
            }
        }

        @Override
        public void onUploadAllFinished(int position, ChatAidl uploads,
                                        boolean CheckFlag) throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onUploadAllFinished(position, uploads.info, CheckFlag);
            }
        }

        @Override
        public void onCancelUpload(int position, ChatAidl uploads, int current)
                throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onCancelUpload(position, uploads.info, current);
            }
        }

        @Override
        public void onPauseUpload(int position, ChatAidl uploads, int current)
                throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onPauseUpload(position, uploads.info, current);
            }
        }

        @Override
        public void onResumeUpload(int position, ChatAidl uploads, int current)
                throws RemoteException {
            // TODO Auto-generated method stub
            if (mUploadListener != null) {
                mUploadListener.onResumeUpload(position, uploads.info, current);
            }
        }

    }
}
